package com.py.framework.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.py.framework.common.Constants;
import com.py.framework.common.controller.SystemController;
import com.py.framework.core.helper.JWTHelper;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.core.utils.BeanUtil;
import com.py.framework.core.utils.DateUtils;
import com.py.framework.entity.UserEntity;
import com.py.framework.service.AuthenticationService;
import com.py.framework.service.UserService;

/**
 * 登录Controller
 * @author Leegern
 * @date   2018年4月27日
 */
@RestController
@RequestMapping("/hy")
public class LoginController extends SystemController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private AuthenticationService authenticationService;
	
	
	/**
	 * @api {post} /hy/login.json 用户登录
	 * @apiName login
	 * @apiVersion 0.0.1
	 * @apiGroup 用户登录 
	 * @apiParam {HttpServletRequest}  request 请求对象
	 * @apiParam {HttpServletResponse}  response 响应对象
	 * @apiParam {String}  username 用户名
	 * @apiParam {String}  password 密码
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} flag 返回结果 true:成功, false:失败
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":0,"data": {"flag":"true"}}
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public RestServiceResult<Map<String, Object>> login(HttpServletRequest request, 
			HttpServletResponse response, String username, String password) {
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
		Date todayDate=DateUtils.convertToDate(dateFormat.format(new Date()));
		RestServiceResult<Map<String, Object>> result = null;
		Map<String, Object> data = null;
		String jdToken = "";
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			result = super.getFailedRestServiceResult("用户名或密码不能为空！");
		} else {
			UserEntity user = userService.getUserByTwoPrincipal(username);
			if (null == user) {
				result = super.getFailedRestServiceResult("用户名不存在！");
			} else {
				if (! password.equals(user.getPassword())) {
					result = super.getFailedRestServiceResult("密码不正确！");
					if(user.getUserType()!=3) {
						if(StringUtils.isBlank(String.valueOf(user.getLogTimes()))) {
							user.setLogTimes(1);
						}else {
							user.setLogTimes(user.getLogTimes()+1);
						}
						user.setErrorTime(todayDate);
						if(user.getLogTimes()>5){
							result = super.getFailedRestServiceResult("账号已被锁定！");	
						}else if(user.getLogTimes()<5&&todayDate.getTime()!=user.getErrorTime().getTime()) {
							user.setLogTimes(1);
							user.setErrorTime(todayDate);
						}
						int i=userService.updateLog(user);
					}
				}else {
					if(StringUtils.isBlank(String.valueOf(user.getLogTimes()))) {
						data = new HashMap<String, Object>();
						try {
							user.setLogTimes(0);
							user.setErrorTime(todayDate);
							int i=userService.updateLog(user);
							data.putAll(BeanUtil.populateBean2Map(user));
							data.remove("password");
							jdToken = JWTHelper.createJWT(String.valueOf(user.getId()), user.getUsername(), Constants.NUMBER_ZERO);
							data.put(Constants.Token, jdToken);
							// 缓存用户会话信息
							authenticationService.putUserSessionData(jdToken, user);
						} catch (Exception e) {
							ExceptionLogger.error(e);
						} 
						result = super.getSuccessRestServiceResult(data);
					}else {
						if(user.getLogTimes()>5 && user.getUserType()!=3) {
							result = super.getFailedRestServiceResult("账号已被锁定！");	
						}else {
							data = new HashMap<String, Object>();
							try {
								user.setLogTimes(0);
								user.setErrorTime(todayDate);
								int i=userService.updateLog(user);
								data.putAll(BeanUtil.populateBean2Map(user));
								data.remove("password");
								jdToken = JWTHelper.createJWT(String.valueOf(user.getId()), user.getUsername(), Constants.NUMBER_ZERO);
								data.put(Constants.Token, jdToken);
								// 缓存用户会话信息
								authenticationService.putUserSessionData(jdToken, user);
							} catch (Exception e) {
								ExceptionLogger.error(e);
							} 
							result = super.getSuccessRestServiceResult(data);
						}
					}
					
				}
			}
		}
		return result;
	}
	/**
	 * @api {post} /hy/updateerrortimes.json 用户解锁
	 * @apiName updateErrorTimes
	 * @apiVersion 0.0.1
	 * @apiGroup 用户解锁
	 * @apiParam {String}  username 用户名
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} flag 返回结果 true:成功, false:失败
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"用户名不存在！","count":0,"data": }
	 */
	@RequestMapping(value = "/updateerrortimes", method = RequestMethod.POST)
	public RestServiceResult<Map<String, Object>> updateErrorTimes(String username) {
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
		Date todayDate=DateUtils.convertToDate(dateFormat.format(new Date()));
		RestServiceResult<Map<String, Object>> result = null;
		UserEntity user = userService.getUserByPrincipal(username);
		if(null==user) {
			result = super.getFailedRestServiceResult("用户名不存在！");
		}else {
			if(user.getLogTimes()>5) {
				user.setLogTimes(0);
				user.setErrorTime(todayDate);
				int i=userService.updateLog(user);
				if(i>0) {
					result = super.getSuccessRestServiceResult();
				}else {
					result = super.getFailedRestServiceResult("账号解锁失败！");
				}
			}else {
				result = super.getFailedRestServiceResult("该账号未被锁定！");
			}
		}
		return result;	
	}
}